import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket=null;
    private  String serverIP;
    private  int serverPort;

    public UdpEchoClient(String ip,int port) throws SocketException {
        serverIP = ip;
        serverPort = port;
        socket=new DatagramSocket();
    }
    //让这个客户端反复从控制台读取用户输入的内容，把这个过程构造成UDP的请求，发给服务器，再读取服务器返回的UDP响应
    //最终显示在客户端屏幕上
    public  void start() throws IOException {
        Scanner scanner=new Scanner(System.in);
        System.out.println("客户端启动");
        while(true){
            //1.从控制台读取用户制定的内容
            System.out.println("->");
            String request= scanner.next();
            //2.构造请求对象，并且发给服务器
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);
            //3.读取服务器的响应，并解析出响应内容
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            //4.显示到屏幕上
            System.out.println(response);


        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",90);
        client.start();
    }















}

